<?php

declare(strict_types=1);

namespace app\api\model;

use app\api\logic\LogicalProcess;
use Monolog\Handler\IFTTTHandler;
use think\facade\Db;
use think\Model;

class Travel
{
    //查询马匹配置
    public function getHorsesConfig()
    {
        $list = Db::name("horses_config")->where("mark", 1)->select();
        return message("操作成功", true, $list);
    }

    //查询游戏配置
    public function getGameConfig()
    {
        $data = Db::name("game_config")->where("mark", 1)->withoutField("create_user,create_time,update_user,update_time,mark")->find();
        return message("操作成功", true, $data);
    }


    //获取当前用户马匹配置
    public function getHorsesData($params)
    {
        $list = Db::name("explore_record")->where("user_id", $params['user_id'])->where("is_over", 0)->order("id desc")->select();
        return message("操作成功", true, $list);
    }

    //购买马匹
    public function buyHorses($params)
    {
        //查询是否有唐僧npc
        $userNpc = Db::name("user_npc")->where("user_id", $params['user_id'])->where("npc_id", 4)->find();
        if (empty($userNpc)) return message("未拥有唐僧npc，请购买后npc后操作", false);

        //查询钱包信息
        $wallet = Db::name("user_wallet")->where("user_id", $params['user_id'])->where("status", 1)->where("type", 1)->find();
        if (empty($wallet)) return message("未查询到钱包信息", false);
        //马匹信息
        $horses = Db::name("horses_config")->where("id", $params['id'])->where("is_del", 0)->find();
        if (empty($horses)) return message("为查询到马匹信息", false);
        //查询用户已获得马匹信息
        $explore = Db::name("explore_record")->where("user_id", $params['user_id'])->where("is_over", 0)->where("horses_id", $params['id'])->count();
        if ($explore >= $horses['max_count']) return message("已达购买最大上限，不可继续购买", false);
        if ($wallet['amount'] < $horses['price']) return message("经书不足,请获得经书后购买", false);
        (new LogicalProcess())->wallletChange($params['user_id'], $horses['price'], 1, 2, 8, "购买马匹");
        //生成购买记录
        Db::name("explore_record")->insert([
            "user_id" => $params['user_id'],
            "horses_id" => $params['id'],
            "is_over" => 0,
            "price" => $horses['price'],
            "all_get_amount" => $horses['amount'],
            "has_books" => 0,
            "summon_time" => datetime(time()),
            "explore_days" => 0,
        ]);
        return message("操作成功", true);
    }

    //今日收益
    public function getTodayEarnings($params)
    {
        //查询用户马匹
        $list = Db::name("explore_record")->where("user_id", $params['user_id'])->where("is_over", 0)->select()->toArray();
        if (empty($list)) return message("未获得马匹", false);
        $amount = 0;
        foreach ($list as $v) {
            $horses = Db::name("horses_config")->where("id", $v['horses_id'])->value("amount");
            $amount += bcdiv($horses, "30", 6);
        }
        return message("操作成功", true, $amount);
    }

    //铸造金箍棒
    public function castJGB($params)
    {
        //查询当前用户是否有猪八戒
        $userNpc = Db::name("user_npc")->where("user_id", $params['user_id'])->where("npc_id", 2)->count();
        if ($userNpc <= 0) return message("未拥有npc，请联系店长购买", false);
        //校验是否有足够的金箍棒碎片
        $wallet = Db::name("user_wallet")->where("user_id", $params['user_id'])->where("status", 1)->where("type", 2)->find();
        if (empty($wallet)) return message("钱包异常，请重试", false);
        if ($wallet['amount'] < $params['total']) return message("余额不足，请获得更多碎片后再铸造", false);
        //查询游戏配置
        $castScale = Db::name("game_config")->where("id", 1)->value("zbj_cast_scale");
        $time = time();
        $count = 0;
        $data = [];
        for ($i = 1; $i <= $params['total']; $i++) {
            $rand = rand(1, 100);
            if ($rand <= $castScale) {
                $count++;
                $data[] = [
                    "user_id" => $params['user_id'],
                    "create_time" => $time,
                    "durability" => 30,
                    "is_use" => 0,
                ];
            }
        }
        Db::name("user_jgb")->insertAll($data);
        //增加铸造记录
        Db::name("zbj_cast_record")->insert([
            "user_id" => $params['user_id'],
            "spend_amount" => $params['total'],
            "success_count" => $count,
            "create_time" => datetime(time()),
        ]);
        (new LogicalProcess())->wallletChange($params['user_id'], $params['total'], 5, 2, 2, "铸造金箍棒");
        return message("操作成功", true, $data);
    }

    //获取铸造金箍棒记录
    public function getCastJGBRecords($params)
    {
        $page = $params['pageNum'] ? $params['pageNum'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        $count = Db::name("zbj_cast_record")->where("user_id", $params['user_id'])->count();
        $list = Db::name("zbj_cast_record")->where("user_id", $params['user_id'])->order("create_time desc")->page((int)$page, (int)$pageSize)->select()->toArray();

        if (empty($list)) return message("操作成功", true, []);
        foreach ($list as &$v) {
            $v['create_time'] = datetime($v['create_time']);
        }
        $arr = ['count' => $count, 'list' => $list];
        return message("操作成功", true, $arr);
    }

    //维修金箍棒
    public function maintainJGB($params)
    {
        $arr = explode(",", $params['ids']);
        //查询游戏配置
        $gameConfig = Db::name("game_config")->where("id", 1)->value("zbj_maintain_total");
        //查询维修的金箍棒
        $userJgb = Db::name("user_jgb")->whereIn("id", $arr)->select()->toArray();
        if (empty($userJgb)) return message("未查询到需维修的金箍棒", false);
        $num = 0;
        // 计算一共要维修的点数
        foreach ($userJgb as $v) {
            if ($v['durability'] >= 30) return message("维修参数异常，请重新选择", false);
            $num += 30 - $v['durability'];
            Db::name("user_jgb")->where("id", $v['id'])->update(['durability' => 30]);
        }
        $amount = bcmul($gameConfig, (string)$num, 6);
        $wallet = Db::name("user_wallet")->where("user_id", $params['user_id'])->where("type", 1)->value("amount");
        if ($amount > $wallet) return message("经书不足，请获取后再维修", false);
        (new LogicalProcess())->wallletChange($params['user_id'], $amount, 7, 2, 1, "维修金箍棒");
        //添加维修记录
        Db::name("zbj_repair_record")->insert([
            "user_id" => $params['user_id'],
            "spend_amount" => $amount,
            "repair_count" => count($userJgb),
            "create_time" => datetime(time()),
        ]);
        return message("操作成功", true);
    }

    //维修金箍棒记录
    public function getRepairJGBRecords($params)
    {
        $page = $params['pageNum'] ? $params['pageNum'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        $count = Db::name("zbj_repair_record")->where("user_id", $params['user_id'])->count();
        $list = Db::name("zbj_repair_record")->where("user_id", $params['user_id'])->order("create_time desc")->page((int)$page, (int)$pageSize)->select()->toArray();

        if (empty($list)) return message("操作成功", true, []);
        foreach ($list as &$v) {
            $v['create_time'] = datetime($v['create_time']);
        }
        $arr = ['count' => $count, 'list' => $list];
        return message("操作成功", true, $arr);
    }

    //大反击游戏信息
    public function getGameInfo($uid)
    {
        //查询游戏配置
        $wearJgb = Db::name("game_config")->where("id", 1)->value("djf_jgb_wear");
        // 获取大反击本期控制的id,根据id查询本期有多少投入
        $dfjRecord = Db::name("dfj_record")->order("create_time desc")->find();

        //所有人投入
        $dfjTotal = Db::name("user_dfj_record")->where("dfj_id", $dfjRecord['id'])->count();
        //当前用户投入
        $userDfjTotal = Db::name("user_dfj_record")->where("dfj_id", $dfjRecord['id'])->where("user_id", $uid)->count();
        //用户金箍棒信息
        $userJgb = Db::name("user_jgb")->where("user_id", $uid)->where("is_use", 1)->where("durability", "<", 30)->count();
        $userJgbCount = Db::name("user_jgb")->where("user_id", $uid)->where("durability", "<", 30)->count();
        //如果该用户未投入金箍棒
        $thirtyEarnings = $scale = 0;
        if ($userDfjTotal > 0) {
            //预计30天奖池
            $divide = bcmul($dfjRecord['total_this'], "30", 6);
            $thirtyEarnings = bcmul(bcdiv((string)$userDfjTotal, (string)$dfjTotal, 6), $divide, 6);
        }

        $currentDate = date('Y-m-d');
        $yesterdayDate = date('Y-m-d', strtotime('-1 day'));
        // 构建 SQL 查询
        $sql = "
            SELECT 
                (t1.total_this - COALESCE(t2.total_this, 0)) AS total_difference
            FROM 
                evt_dfj_record t1
            LEFT JOIN 
                 evt_dfj_record t2 ON DATE(t2.create_time) = DATE_SUB(DATE(t1.create_time), INTERVAL 1 DAY)
            WHERE 
                DATE(t1.create_time) = :current_date OR DATE(t2.create_time) = :yesterday_date;
        ";
        $data = Db::query($sql, [
            'current_date' => $currentDate,
            'yesterday_date' => $yesterdayDate,
        ]);
        // 执行查询

        $res = [
            "thirtyEarnings" => $thirtyEarnings,
            "todayEarnings" => $dfjRecord['total_this'],
            "totalGolden" => $dfjTotal,
            "diffEarnings" => $data[0]['total_difference'],
            "jgbTotal" => $userDfjTotal,
            "allJgb" => $userJgbCount,
            "usableJgb" => $userJgb
        ];
        return message("操作成功", true, $res);
    }


    //用户大反击压注
    public function userDfjBetOn($params)
    {
        // 1. 校验用户拥有的金箍棒是否在耐久充足的情况下满足数量,并且已经取出来了
        // 查询出来玩家所拥有的金箍棒(耐久大于本息需要消耗的)
        $wearJgb = Db::name("game_config")->where("id", 1)->value("djf_jgb_wear");
        //本次大反击数据
        $dfjRecord = Db::name("dfj_record")->where("is_over", 0)->find();
        if (empty($dfjRecord)) return message("暂不支持操作", false);
        //玩家可用金箍棒
        $userJgb = Db::name("user_jgb")->where("user_id", $params['user_id'])->where("durability", ">=", $wearJgb)->where("is_use", false)->select()->toArray();
        if (count($userJgb) < $params['num']) return message("金箍棒数量不足", false);
        for ($i = 0; $i < $params['num']; $i++) {
            Db::name("user_jgb")->where("id", $userJgb[$i]['id'])->update(['is_use' => true, 'durability' => $userJgb[$i]['durability'] - $wearJgb]);
            Db::name("user_dfj_record")->insert([
                "dfj_id" => $dfjRecord['id'],
                "jgb_id" => $userJgb[$i]['id'],
                "user_id" => $userJgb[$i]['user_id'],
                "create_time" => time(),

            ]);
        }
        return message("操作成功", true);
    }

    //获取本周和上周大反击记录
    public function getWeekDFJRank($params)
    {

        //获取本用户信息
        $userInfo = Db::name("member")->where("id", $params['user_id'])->field("nickname,avatar")->find();
        //获取本周记录
//        $thisWeek = Db::name("member_wallet_log")->whereTime("create_time", "week")->field("sum(amount) as amount,uid")->order("amount desc")->group("uid")->where("category", 1)->where("type", 6)->select()->toArray();
        $thisWeek = Db::name("member_wallet_log")->whereTime("create_time", "week")->field("sum(amount) as amount,uid")->order("amount desc")->group("uid")->select()->toArray();
        $thisData = $lastData = [];
        $myIndex = $total = $lastIndex = $lastTotal = 0;
        if (!empty($thisWeek)) {
            foreach ($thisWeek as $k => $v) {
                $info = Db::name("member")->where("id", $v['uid'])->field("avatar,nickname")->find();
                if ($v['uid'] == $params['user_id']) {
                    $myIndex = $k + 1;
                    $total = $v['amount'];
                }
                $thisData[] = [
                    "userId" => $v['uid'],
                    "nickName" => $info["nickname"],
                    "total" => $v['amount'],
                    'avatar' => get_image_url($info['avatar'])
                ];
            }
        }
        $thisInfoData = [
            "userId" => $params['user_id'],
            "total" => $total,
            "nickName" => $userInfo['nickname'],
            "avatar" => get_image_url($userInfo['avatar']),
            "rankNum" => $myIndex,
        ];
        //获取上周记录
//        $thisWeek = Db::name("member_wallet_log")->whereTime("create_time", "week")->select()->toArray();
        $lastWeek = Db::name("member_wallet_log")->whereTime("create_time", "last week")->field("sum(amount) as amount,uid")->order("amount desc")->group("uid")->where("category", 1)->where("type", 6)->select()->toArray();
        if (!empty($lastWeek)) {
            foreach ($lastWeek as $k => $v) {
                $info = Db::name("member")->where("id", $v['uid'])->field("avatar,nickname")->find();
                if ($v['uid'] == $params['user_id']) {
                    $lastIndex = $k + 1;
                    $lastTotal = $v['amount'];
                }
                $lastData[] = [
                    "userId" => $v['uid'],
                    "nickName" => $info["nickname"],
                    "total" => $v['amount'],
                    'avatar' => get_image_url($info['avatar'])
                ];
            }
        }
        $lastInfoData = [
            "userId" => $params['user_id'],
            "total" => $lastTotal,
            "nickName" => $userInfo['nickname'],
            "avatar" => get_image_url($userInfo['avatar']),
            "rankNum" => $lastIndex,
        ];
        return message("操作成功", true, ['thisData' => $thisData, 'thisInfoData' => $thisInfoData, 'lastWeek' => $lastData, 'lastInfoData' => $lastInfoData]);
    }

    //查询大反击记录
    public function getDFJRecords($params)
    {
        $page = $params['pageNum'] ? $params['pageNum'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        //查询当前用户钱包变动记录
        $list = Db::name("member_wallet_log")->where("uid", $params['user_id'])->where("type", 6)->where("category", 1)->where("change", 1)->page($page,$pageSize)->select()->toArray();
        $arr = [];
        if (empty($list)) return message("操作成功", true);
        foreach ($list as $v) {
            //获取时间
            $date = datetime(strtotime('-1 day', $v['create_time']), "Y-m-d");
            //查询dfj记录
            $dfjRecord = Db::name("dfj_record")->where("date", $date)->find();

            //查询金箍棒数据
            $userJgb = Db::name("user_dfj_record")->where("dfj_id", $dfjRecord['id'])->where("user_id", $params['user_id'])->count();
            $arr[] = [
                "id" => $dfjRecord['id'],
                "date" => $dfjRecord['date'],
                "amount" => $v['amount'],
                "useJgb" => $userJgb,
            ];
        }
        return message("操作成功", true, $arr);
    }


    //统计收益 今日收益 七天之前收益 30天之前收益 昨日收益
    public function getCensusInfo($params)
    {
        //查询当前未完成的大反击
        $dfjRecord = Db::name("dfj_record")->order("create_time desc")->find();

        $current = $seven = $month = $yesterday = 0;
        //查询当前总投入
        $currentPut = Db::name("user_dfj_record")->whereTime("create_time", 'today')->count();
        //七天之前总投入
        $sevenPut = Db::name("user_dfj_record")->whereTime("create_time", '<', '-7 days')->count();
        //30天之前数据
        $monthPut = Db::name("user_dfj_record")->whereTime("create_time", '<', '-30 days')->count();
        //昨天之前数据
        $yesterdayPut = Db::name("user_dfj_record")->whereTime("create_time", 'yesterday')->count();
        //所有人投入
        $totalCount = Db::name("user_dfj_record")->where("dfj_id", $dfjRecord['id'])->count();
        //查询当前用户投入
        $userDfjCount = Db::name("user_dfj_record")->where("dfj_id", $dfjRecord['id'])->where("user_id", $params['user_id'])->count();
        if ($userDfjCount <= 0) return message('操作成功', true, [
            "current" => $current,
            "seven" => $seven,
            "month" => $month,
            "yesterday" => $yesterday,
        ]);
        $divide = bcdiv((string)$userDfjCount, (string)$totalCount, 6);
        $current = bcmul((string)$currentPut, $divide, 6);
        $seven = bcsub($current, bcmul((string)$sevenPut, $divide, 6), 6);
        $month = bcsub($current, bcmul((string)$monthPut, $divide, 6), 6);
        $yesterday = bcsub($current, bcmul((string)$yesterdayPut, $divide, 6), 6);
        return message('操作成功', true, [
            "current" => $current,
            "seven" => $seven,
            "month" => $month,
            "yesterday" => $yesterday,
        ]);
    }

    //悟空收益查询
    public function queryEarnings($user_id)
    {
        $res = (new LogicalProcess())->queryEarnings($user_id);
        return message($res['msg'],$res['code'],$res['data']);
    }

}